package cn.lblbc.flashlight

import android.Manifest
import android.content.pm.PackageManager
import android.hardware.camera2.CameraManager
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {
    private lateinit var cameraManager: CameraManager
    private var cameraId: String? = null
    private var isFlashOn = false
    private lateinit var powerButton: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 设置全屏
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        supportActionBar?.hide()
        
        setContentView(R.layout.activity_main)
        
        // 初始化视图
        initViews()
        
        // 检查相机权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE)
        } else {
            initCamera()
        }
    }
    
    private fun initViews() {
        powerButton = findViewById(R.id.power_button)
        powerButton.setOnClickListener {
            toggleFlashlight()
        }
    }
    
    private fun initCamera() {
        cameraManager = getSystemService(CAMERA_SERVICE) as CameraManager
        try {
            cameraId = cameraManager.cameraIdList[0] // 通常后置摄像头是第一个
        } catch (e: Exception) {
            Toast.makeText(this, "无法访问摄像头", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun toggleFlashlight() {
        if (cameraId == null) {
            Toast.makeText(this, "设备不支持闪光灯", Toast.LENGTH_SHORT).show()
            return
        }
        
        try {
            cameraManager.setTorchMode(cameraId!!, !isFlashOn)
            isFlashOn = !isFlashOn
            updateButtonState()
        } catch (e: Exception) {
            Toast.makeText(this, "无法开启闪光灯", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun updateButtonState() {
        if (isFlashOn) {
            powerButton.setImageResource(R.drawable.power_on)
        } else {
            powerButton.setImageResource(R.drawable.power_off)
        }
    }
    
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            CAMERA_PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initCamera()
                } else {
                    Toast.makeText(this, "需要相机权限才能使用手电筒功能", Toast.LENGTH_LONG).show()
                    finish()
                }
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 关闭手电筒
        if (isFlashOn && cameraId != null) {
            try {
                cameraManager.setTorchMode(cameraId!!, false)
            } catch (e: Exception) {
                // 忽略错误
            }
        }
    }
    
    companion object {
        private const val CAMERA_PERMISSION_REQUEST_CODE = 100
    }
}